package org.winexpress

import grails.converters.deep.JSON
import org.codehaus.groovy.grails.web.json.JSONObject;
import org.codehaus.groovy.grails.web.json.JSONArray;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;


class CartManagementController {
    
    // resuable methods available
    def getProductList() {
        // consume winexpress server web service
        def txt = new URL("http://localhost:8080/WineXpress/product/").text
        
        if (txt.getAt(0) == '{') {
            JSONObject o = new JSONObject(txt)
            if (o.has("404")) {
                if (o.get("404") == true) {
                    flash.message = 'No products.<br/><br/>'
                    try {
                        redirect(uri:"/404")
                    }
                    catch (CannotRedirectException) {
                        println 'already redirected...'
                    }
                }
            }
        }
        else {
            JSONArray arr = new JSONArray(txt)
            ArrayList<Product> productList = new ArrayList<Product>()

            arr.each()
            {
                Product p = new Product()
                p.id = it.id
                p.productName = it.productName
                p.description = it.description
                p.imageUrl = it.imageUrl
                p.size = it.size
                p.costPrice = it.costPrice
                p.sellingPrice = it.sellingPrice
                p.stockCount = it.stockCount
                
                ProductType pt = it.productType
                p.productTypeName = pt.productTypeName
                
                productList.add(p)
            }

            return productList
        }
    }
    
    def getSingleProduct(id) {
       
        // consume winexpress server web service
        def txt = new URL("http://localhost:8080/WineXpress/product/" + id).text
        
        if (txt.getAt(0) == '{') {
            JSONObject o = new JSONObject(txt)
            if (o.has("404")) {
                if (o.get("404") == true) {
                    flash.message = 'No specified product found.<br/><br/>'
                    try {
                        redirect(uri:"/404")
                    }
                    catch (CannotRedirectException) {
                        println 'already redirected...'
                    }
                }
            }
            else {
                Product p = new Product()
                p.id = o.get("id")
                p.productName = o.get("productName")
                p.description = o.get("description")
                p.imageUrl = o.get("imageUrl")
                p.size = o.get("size")
                p.costPrice = o.get("costPrice")
                p.sellingPrice = o.get("sellingPrice")
                p.stockCount = o.get("stockCount")
                
                ProductType pt = o.get("productType")
                p.productTypeName = pt.productTypeName
                
                return p
            }
        }
        else {
            flash.message = 'No specified product found.<br/><br/>'
            redirect(uri:"/")
        }
    }
    
    
    def getSingleCart(id) {
       
        // consume winexpress server web service
        def txt = new URL("http://localhost:8080/WineXpress/cart/" + session.cartId).text
        
        if (txt.getAt(0) == '{') {
            JSONObject o = new JSONObject(txt)
            if (o.has("404")) {
                if (o.get("404") == true) {
                    flash.message = 'No specified cart found.<br/><br/>'
                    try {
                        redirect(uri:"/404")
                    }
                    catch (CannotRedirectException) {
                        println 'already redirected...'
                    }
                }
            }
            else {
                ShoppingCart sc = new ShoppingCart()
                sc.id = o.get("id")
//                sc.creationDate = o.get("creationDate")
//                sc.modifiedDate = o.get("modifiedDate")
                sc.customerId = o.get("customerId")
                sc.uniqueKey = o.get("uniqueKey")
                
                return sc
            }
        }
        else {
            flash.message = 'No specified cart found.<br/><br/>'
            redirect(uri:"/")
        }
    }
    
    def getCartItems(id) {
       
        // consume winexpress server web service
        def txt = new URL("http://localhost:8080/WineXpress/cart/" + session.cartId + "/item/").text
        
        println 'cartItems.count():: ' + txt
        
        
        if (txt.getAt(0) == '{') {
            JSONObject o = new JSONObject(txt)
             println '1111'
            if (o.has("404")) {
                if (o.get("404") == true) {
                    flash.message = 'No cart items.<br/><br/>'
                    try {
                        redirect(uri:"/404")
                    }
                    catch (CannotRedirectException) {
                        println 'already redirected...'
                    }
                }
            }
        }
        else {
//            println '222'
//            JSONArray arr = new JSONArray(txt)
//            println arr.cartItem
////            println newArr
            ArrayList<CartItem> itemList = new ArrayList<CartItem>()
//
//            arr2.each()
//            {
//                CartItem ci = new CartItem()
//                ci.id = it.id
//                ci.productId = it.productId
//                Product p = getSingleProduct(ci.productId)
//                ci.productName = p.productName
//                ci.sellingPrice = p.sellingPrice
//                ci.quantity = it.quantity
////                ci.cartId = it.cartId
//                itemList.add(ci)
//            }

            return itemList
        }
    }
    

    def shoppingCartRetrieve = { 
        ShoppingCart cart = getSingleCart()
        CartItem cartItems = getCartItems(cart.id)
//        println 'cartItems.count()' + cartItems.count()
//        cartItems.each() {
//            println it.sellingPrice
//            println it.quantity
//            def sub = it.sellingPrice * it.quantity
//            it.subtotal = sub
//        }

        def txt = new URL("http://localhost:8080/WineXpress/totalprice?username=" + session.customerUsername).text
        
        JSONObject o = new JSONObject(txt)
        def totalPrice = o.get("totalprice")
        def items = o.get("products")
        
        session.cartItemCount = cartItems.count()

        [shoppingCartId:cart.id, cartItems:cartItems, cart:cart, totalPrice:totalPrice, items:items]
    }
    
    
    
    // REST-related operations for accessing WineXpress Server (for clearer view only)
    // GET
    
    // PUT
    
    // DELETE
    
    // POST
    def addToCart = {
        println 'addToCart'
        
        // get form values
        def productId = params['id'] 
        def quantity = params['quantity']
        println 'quantity:: ' + quantity
        
        // create a JSONObject to send to winexpress server
        JSONObject o = new JSONObject()
        o.put("productId",productId)
        o.put("quantity",quantity)
        o.put("cartId",session.cartId)
        o.put("customerId",session.customerId)
        
        // create cart with no customer id
        if (session.customerId == null) {
            flash.message = "Please register for an account to facilitate check out and saving of cart." + 
                "<br/><a href='http://localhost:8088/WineXpressClient/memberRegistration'/>Click here to register</a> " + 
                "or <a href='http://localhost:8088/WineXpressClient/memberLogin'/>login</a> now!"
            redirect(uri:"/retrieveProductDetail?id=" + productId)
//            println 'no customer login'
//            // to create use POST
//            HttpClient httpclient = new DefaultHttpClient()
//            HttpResponse response
//            // consume winexpress server web service
//            HttpPost httppost = new HttpPost("http://localhost:8080/WineXpress/shoppingCart/") // WineXpress Server's URI
//            httppost.setHeader("Content-Type", "text/json")
//
////            HttpEntity reqEntity = new StringEntity(data, "UTF-8")
////            reqEntity.setContentType("text/json")
////            reqEntity.setChunked(true)
//            StringEntity se = new StringEntity(o.toString())          
//            httppost.setEntity(se);                   
//            response = httpclient.execute(httppost);
//            
//            // get response code
//            StatusLine status = response.getStatusLine()
//            int statusCode = status.getStatusCode()
//
//            println 'special cart: ' + statusCode
//            if (statusCode == 201) {
//                flash.message = "Shopping Cart successfully created."
//                try {
//                    redirect(uri:"/retrieveProductDetail")
//                }
//                catch (CannotRedirectException) {
//                    println 'already redirected...'
//                }
//            }
//            if (statusCode == 400) {
//                flash.message = "Shopping Cart could not be created. Please try again."
//                try {
//                    redirect(uri:"/retrieveProductDetail")
//                }
//                catch (CannotRedirectException) {
//                    println 'already redirected...'
//                }
//            }

        }
        else {
            println 'is customer login'
            // to create use POST
            HttpClient httpclient = new DefaultHttpClient()
            HttpResponse response
            // consume winexpress server web service
            println "http://localhost:8080/WineXpress/cart/" + session.cartId + "/item/"
            HttpPost httppost = new HttpPost("http://localhost:8080/WineXpress/cart/" + session.cartId + "/item/") // WineXpress Server's URI
            StringEntity se = new StringEntity(o.toString())          
            httppost.setEntity(se);          
            response = httpclient.execute(httppost);
            
            // get response code
            StatusLine status = response.getStatusLine()
            int statusCode = status.getStatusCode()
            println 'cart status code: ' + statusCode
            
            if (statusCode == 200) {
                flash.message = "Item successfully updated."
            }
            if (statusCode == 201) {
                flash.message = "Item successfully added."
            }
            if (statusCode == 302) {
                flash.message = "Item successfully added."
            }
            if (statusCode == 400) {
                flash.message = "Item could not be added."
            }
            redirect(uri:"/retrieveProductDetail?id=" + productId)
        }
    }
    
    def checkOutShoppingCart = {
        
    }
}
